import { getRequest } from "./api";


export const initMenu = (router, store) => {
    if (store.state.routes.length > 0) {
        return;
    }
    getRequest('/system/cfg/menu').then(data => {
        if (data) {
            //格式化router
            let fmtRoutes = formatRoutes(data);
            //添加到router
            router.addRoutes(fmtRoutes);
            // 将数据存入vuex
            store.commit('initRoutes', fmtRoutes);
        }
    })
}


export const formatRoutes = (routes => {
    let fmtRoutes = [];
    if (!routes) {
        return;
    }
    routes.forEach(router => {
        let {
            path,
            name,
            component,
            iconCls,
            children,
        } = router;
        if (children && children instanceof Array) {
            // 递归
            children = formatRoutes(children);
        }
        let fmRoutes = {
            path: path,
            name: name,
            iconCls, iconCls,
            children, children,
            component(resolve) {
                if(component.startsWith('Home')) {
                    require(['../views/' + component + '.vue'], resolve);
                }else if(component.startsWith('HomeNews')) {
                    require(['../views/' + component + '.vue'], resolve);
                }else if(component.startsWith('Books')) {
                    require(['../views/books/' + component + '.vue'], resolve);
                }else if(component.startsWith('News')) {
                    require(['../views/news/' + component + '.vue'], resolve);
                }else if(component.startsWith('Rent')) {
                    require(['../views/rent/' + component + '.vue'], resolve);
                }else if(component.startsWith('Resource')) {
                    require(['../views/resource/' + component + '.vue'], resolve);
                }else if(component.startsWith('Sys')) {
                    require(['../views/sys/' + component + '.vue'], resolve);
                }                
            }

        }
        fmtRoutes.push(fmRoutes);
    });
    return fmtRoutes;
})